import axios from 'axios';//引入axios
import route from '../router';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import qs from 'qs'
import crypto from 'crypto';
axios.defaults.withCredentials=true;
import { Message } from 'element-ui'
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 发送请求之前做一些处理
  NProgress.start();

  return config
},error => {
  if (error.response) {
    switch (error.response.status) {
      case 404:
        Message({
          message: "请求404！",
          type: "error"
        })
        break
      case 500:
        Message({
          message:"请求500！",
          type: "error"
        });
        break
    }
  }
  return Promise.reject({ code: '-100', message: '网络异常请稍后再试！' })
})

axios.interceptors.response.use(function (response) {
  NProgress.done();
  if(response.headers['content-type'] == "image/png"){
    //这是图片验证码
  }else{
    if(response.data.code != 1){
      Message({
        message: response.data.msg,
        type: "error"
      })
      if(response.data.code == 11000){
          window.location.href = '/'
      }
    }
    return response
  }
}, function (err) {
  return Promise.reject(err)
});

export function _http(url , options) {
  let opt = options || {};

  return new Promise((resolve,reject) => {
    axios({
      method: opt.type || 'post',
      url: process.env.API_HOST+url,
      params: opt.params || {},
      data: opt.data ? qs.stringify(opt.data) : {},
      // headers: opt.headers || {'Content-Type': 'application/x-www-form-urlencoded'},
      headers:{'Content-Type': 'application/x-www-form-urlencoded'},
      
      withCredentials:true,
    })
      .then(response => {
        resolve(response.data)
      }).catch(err =>{
      reject(err)
    })
  })

}

